package org.fastsyncer.rest.controller;

import java.io.File;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.rest.interceptor.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录验证处理
 * 
 * @ClassName: AuthenticateController
 * @Description: 登录验证，注销
 * @author AE86
 * @date: 2017年7月7日 上午10:03:33
 */
@Controller
@RequestMapping(value = "/authenticate")
public class AuthenticateController {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticateController.class);

    /**
     * 首页地址
     */
    private static final String MAIN_URL = ApplicationUtil.getKey(CommonConstant.SERVER_SERVICE_ADDRESS);

    /**
     * 认证地址
     */
    private static final String LOGIN_URL = ApplicationUtil.getKey(CommonConstant.SERVER_SERVICE_ADDRESS_AUTHENTICATE);

    @RequestMapping("")
    public String index(ModelMap model) {
        return "login/login";
    }

    /**
     * oauth授权确认
     * 
     * @Title: authConfirm
     * @Description: 权限验证
     * @param request
     * @param response
     * @param appIds 应用系统ID
     * @param appName 应用系统名称
     * @return
     */
    @RequestMapping(value = "/oauth", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public RestResult oauth(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "appId", required = false) String appId,
            @RequestParam(value = "appName", required = false) String appName) {
        try {
            //写入Appid
            String appIdKey = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPID);
            String appNameKey = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPNAME);
            appId = StringUtils.isBlank(appId) ? "all" : appId;
            HttpSession session = request.getSession();
            session.setAttribute(appIdKey, appId);
            // 判断应用名称
            if (StringUtils.isNotBlank(appName)) {
                Charset charset = File.separator.equals("/") ? Charset.forName("iso-8859-1") : Charset.forName("GBK");
                String aName = new String(appName.getBytes(charset), "UTF-8");
                session.setAttribute(appNameKey, aName);
            }
            // 重定向主页
            response.sendRedirect(MAIN_URL);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        }
        return RestResult.restFail("oauth登录失败,请联系管理员.");
    }

    /**
     * 授权确认
     * 
     * @Title: authConfirm
     * @Description: 权限验证
     * @param response
     * @param username
     *            帐号
     * @param userpwd
     *            密码
     * @return: RestResult
     */
    @RequestMapping(value = "/login", method = { RequestMethod.POST })
    @ResponseBody
    public RestResult login(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "username") String username,
            @RequestParam(value = "userpwd") String userpwd) {
        try {
            // 生成认证票据,如果验证失败，抛出异常
            Ticket.createTicket(request, response, username, userpwd);
            logger.info("login success!");
            return RestResult.restSuccess("login success!");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        }
        return RestResult.restFail("对不起,您输入的帐号或密码错误");
    }

    /**
     * 注销
     * 
     * @Title: logout
     * @Description: 注销登录
     * @param ticket
     *            ticket票据ID
     * @return: RestResult
     */
    @RequestMapping(value = "/logout", method = { RequestMethod.GET, RequestMethod.POST })
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 注销用户票据
            Ticket.removeTicket(request.getSession());
            // 跳转至认证页面
            response.sendRedirect(LOGIN_URL);
            logger.info("logout success!");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        }
    }

    @RequestMapping(value = "/test", method = { RequestMethod.POST })
    @ResponseBody
    public RestResult test(String name) {
        try {
            logger.info("name:" + name);
            return RestResult.restSuccess("test success!");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        }
        return RestResult.restFail("对不起,您输入的帐号或密码错误");
    }

}
